import {useDrop} from "react-dnd";
import {debounceHandle} from "../../utils/throttle.ts";
import {useState} from "react";
import {getComponentById, useComponentsStore} from "../../stores/components.tsx";
import {ContainerDndAccept} from "../materials/DnDAccept.tsx";

export interface useMoveDropProps {
    dropComponentId: number // 被放置的组件id
    parentId: number, // 被放置组件的父组件id
}

export const MoveDrop = (props: useMoveDropProps) => {
    const {dropComponentId, parentId,} = props
    const [position, setPosition] = useState('')
    const {insertComponentByPosition, components} = useComponentsStore()
    const [{isOverB}, dropBefore] = useDrop({
        accept: [...ContainerDndAccept],
        drop: (item: any, monitor) => {
            setPosition('')
            // 判断是否已经拖拽过
            const didDrop = monitor.didDrop()
            if (didDrop || item.id === dropComponentId) return;
            if (item.dragType === 'move') {
                insertComponentByPosition(getComponentById(item.id, components)!, dropComponentId, parentId, 'before')
            }
        },
        hover: (item: any) => {
            if (item.id === dropComponentId) return;
            if(position !== 'before') setPosition('before')
            if(position !== ""){
                debounceHandle(() => {
                    setPosition('')
                }, 200)
            }
        },
        collect: (monitor) => ({
            isOverB: monitor.isOver(), // 获取当前是否处于over状态
        })
    })

    const [{ isOverA }, dropAfter] = useDrop({
        accept: [...ContainerDndAccept], // 接受所有,
        drop: (item: any, monitor) => {
            setPosition('')
            // 判断是否已经拖拽过
            const didDrop = monitor.didDrop()
            if (didDrop || item.id === dropComponentId) return;
            if (item.dragType === 'move') {
                insertComponentByPosition(getComponentById(item.id, components)!, dropComponentId, parentId, 'after')
            }
        },
        hover: (item: any) => {
            if (item.id === dropComponentId) return;
            setPosition('after')
            debounceHandle(() => {
                setPosition('')
            }, 200)
        },
        collect: (monitor) => ({
            isOverA: monitor.isOver(), // 获取当前是否处于over状态
        })
    })

    return (
        <div className={'absolute top-0 left-0 flex h-full w-full z-10'}>
            <div ref={dropBefore}
                 className={`flex-1 w-[50%] h-full ${position === 'before' && isOverB ? 'border-l-[2px] border-[blue]' : ''}`}></div>
            <div ref={dropAfter}
                 className={`flex-1 w-[50%] h-full ${position === 'after' && isOverA ? 'border-r-[2px] border-[blue]' : ''}`}></div>
        </div>
    )
}